import {
    GET
} from './utils/methods';
import api from './network/api';
App({
    $api: api,
    onLaunch: function (query) {
        const app = this;
        // // 展示本地存储能力
        // var logs = wx.getStorageSync('logs') || []
        // logs.unshift(Date.now())
        // wx.setStorageSync('logs', logs)
        // // 登录
        if (query.query.deptId) {
            this.globalData.codeDeptId = query.query.deptId;
            this.globalData.deptId = query.query.deptId;

        }
        this.login();
        // 获取用户信息
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            this.globalData.userInfo = res.userInfo
                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            if (this.userInfoReadyCallback) {
                                this.userInfoReadyCallback(res)
                            }
                        }
                    })
                }
            }
        })

        /**
         * 获取当前的机型如果是 iPhone X 或以上机型
         * （ 则空余出底部空间 ）
         */
        wx.getSystemInfo({
            success: (result) => {
                app.globalData.is_iphonex = result.model.indexOf('iPhone X') > -1
            },
        })
        // this.login()
    },

    onShow: async function (query) {
        console.log('app query', query)
        const app = this;
        console.log(app)

        wx.checkSession({
            fail() {
                app.login()
            }
        });
    },

    // 获取小程序login code
    getWxCode: function () {
        return new Promise(resolve => {
            wx.login({
                success: res => resolve(res.code)
            });
        });
    },
    /**
     * 发送登录请求
     * @param { string } code 微信登录的 code 
     */
    miniLogin: function (code) {
        return new Promise((resolve,reject) => {
            const params = {
                grant_type: 'authorization_code',
                alias: app.globalData.config.alias,
                code: code,
                deptId: app.globalData.deptId
            };
            this.$api.miniLogin(params)
            .then(res => {
              resolve(res);
              wx.setStorageSync('logindata', res.data)
            })
            .catch(error => {
              reject(error);
            });
        });
    },
    /**
     * 储蓄 sessionId
     * @param { string } sessionId 
     */
    setSessionId: function (sessionId) {
        let header = {};
        header.Cookie = 'JSESSIONID=' + sessionId;
        wx.setStorageSync("cookie", header);
    },

    getUsersInfo: function () {
        return new Promise(resolve => {
            this.globalData.userList = []
            this.$api.getUserInfos().then(res=>{
              console.log(res);
              this.globalData.userList = res.data
              resolve()
            })
            // this.$api.getUserInfo().then(res => {
            //     console.log('res', res)
            //     this.globalData.userList = res.data
            //     resolve()
            // })
        })

    },
    login: async function () {
        const wxCode = await this.getWxCode();
        const loginResult = await this.miniLogin(wxCode);
        app.globalData.wxUser=loginResult.data

        console.log('loginResult', loginResult)
        // if (loginResult.data.miniBackEndUrl && loginResult.data.miniBackEndUrl != this.globalData.config.server
        //     && this.globalData.config.server.indexOf('xcxtest')==-1
        //     )
        if(loginResult.status==500){
            return Promise.reject(); 
        }
        if (loginResult.data.miniBackEndUrl && loginResult.data.miniBackEndUrl != this.globalData.config.server
        ) {
            this.globalData.config.server = loginResult.data.miniBackEndUrl;
            this.login();
        }
        if (loginResult.code !== 0) return Promise.reject();
        const {
            code,
            ptDefaultDeptId,
            ptDefaultQueueId,
            ptDefaultUserId,
            sessionId,
            mobile,
            ptAccountId,
            openid
        } = loginResult.data;
        console.log("loginResult.data+++++++++++++++++++++",loginResult.data);
        this.setSessionId(sessionId);
        this.globalData.deptId = ptDefaultDeptId
        this.globalData.queueId = ptDefaultQueueId;
        this.globalData.userId = ptDefaultUserId;
        this.globalData.userMobile = mobile;
        this.globalData.account = ptAccountId;
        this.globalData.openid = openid;
        await this.getUsersInfo()
        return Promise.resolve(loginResult);

    },

    // refresh: function () {
    //     var that = this;
    //     const app = this;
    //     setInterval(function () {
    //         wx.checkSession({
    //             fail() {
    //                 wx.login({
    //                     success: res => {
    //                         // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //                         if (res.code) {
    //                             that.globalData.code = res.code
    //                             wx.request({
    //                                 url: app.getUrl("wechat/oauth/miniLogin"), //仅为示例，并非真实的接口地址
    //                                 method: "GET",
    //                                 data: {
    //                                     grant_type: "authorization_code",
    //                                     alias: app.globalData.config.alias,
    //                                     code: res.code
    //                                 },
    //                                 success: res => {
    //                                     if (res.data.code == 0) {
    //                                         if (res.data.data.ptDefaultDeptId) {
    //                                             app.globalData.deptId = res.data.data.ptDefaultDeptId
    //                                         }
    //                                         // app.globalData.queueId = res.data.data.ptDefaultQueueId;
    //                                         var header = {};
    //                                         header.Cookie = 'JSESSIONID=' + res.data.data.sessionId;
    //                                         wx.setStorageSync("cookie", header);
    //                                         // app.globalData.userId = res.data.data.ptDefaultUserId;
    //                                         app.globalData.userMobile = res.data.data.mobile;
    //                                         app.globalData.account = res.data.data.ptAccountId;
    //                                         app.globalData.openid = res.data.data.openid;
    //                                         wx.request({
    //                                             url: app.getUrl('/xcx/pt/getUsersInfo'),
    //                                             method: 'GET',
    //                                             header: wx.getStorageSync('cookie'),
    //                                             success(res) {
    //                                                 if (res.data.code == 0 || res.data.code == 200) {
    //                                                     app.globalData.userList = res.data.data
    //                                                 }
    //                                             }
    //                                         })
    //                                         if (!res.data.data.miniBackEndUrl && !app.globalData.forwarded) {
    //                                             app.globalData.config.server = app.globalData.config.oriServer;
    //                                             app.globalData.forwarded = true;
    //                                             app.globalData.definedUrl = true;
    //                                             // setTimeout(() => app.login(app), 1000);
    //                                         } else if (res.data.data.miniBackEndUrl && res.data.data.miniBackEndUrl != app.globalData.config.server) {
    //                                             app.globalData.definedUrl = false;
    //                                             app.globalData.forwarded = true;
    //                                             app.globalData.config.server = res.data.data.miniBackEndUrl;
    //                                             setTimeout(() => app.login(app), 1000);
    //                                         } else {
    //                                             app.globalData.forwarded = true;
    //                                             app.globalData.definedUrl = true;
    //                                         }
    //                                     } else {
    //                                         setTimeout(() => app.login(app), 1000);
    //                                     }
    //                                 }
    //                             })
    //                         }
    //                     }
    //                 });
    //             }
    //         })
    //     }, 10 * 60 * 500);
    // },
    getUrl: function (url) {
        if (!url.startsWith('/')) {
            url = "/" + url
        }
        return this.globalData.config.server + url;
    },

    getTableUrl: function (url) {
      if (!url.startsWith('/')) {
          url = "/" + url
      }
      return this.globalData.config.tableServer + url;
  },





    // 请求量表接口时使用
    getWebUrl: function (url) {
        if (!url.startsWith('/')) {
            url = "/" + url
        }
        return this.globalData.config.webServer + url;
    },
    getEducationUrl: function (url) {
        if (!url.startsWith('/')) {
            url = "/" + url
        }
        return this.globalData.config.educationServer + url;
    },
    //书写全局变量
    globalData: {
        code: null,
        currentPatient: null,
        hospitalInfo: null,
        userInfo: null,
        userId: null,
        queueId: null,
        userMobile: null,
        deptId: null,
        openid: null,
        codeDeptId: null,
        forwarded: false,
        tabIndex: 0,
        statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
        header: {
            'Cookie': ''
        },
        userList: null,
        safe_bottom: 0,
        retryTime: 0,
      
     

      config: {
        alias: "huerai",
        server: "https://children.huerai.com",
        oriServer: "https://children.huerai.com",
        educationServer: "https://children.huerai.com",
        webServer: "https://children1.huerai.com",
        tableServer:"https://children1.huerai.com/huerai",
      },

      // config: {
      //   alias: "huerai",
      //   server: "http://jiyuan.huerai.com/bbcareDeploy",
      //   oriServer: "http://jiyuan.huerai.com/bbcareDeploy",
      //   educationServer: "http://jiyuan.huerai.com/bbcareDeploy",
      //   webServer: "http://jiyuan1.huerai.com",
      //   tableServer:"http://jiyuan1.huerai.com/huerai",
      // },

      

      // config: { 
      //   alias: "huerai",
      //   server: "http://local.aierpeihu.com:10066/bbcareDeploy",
      //   oriServer: "http://local.aierpeihu.com:10066/bbcareDeploy",
      //   educationServer: "http://local.aierpeihu.com:10066/bbcareDeploy",
      //   webServer: "http://local.aierpeihu.com:10022",
      //   tableServer:"http://local.aierpeihu.com:10062"
      // },
      
      // config: { 
      //   alias: "huerai",
      //   server: "http://localhost:88/bbcareDeploy",
      //   oriServer: "http://localhost:88/bbcareDeploy",
      //   educationServer: "http://localhost:88/bbcareDeploy",
      //   webServer: "http://localhost:9020",
      //   tableServer:"http://localhost:83/huerai"
      // },

      // config: { 
      //   alias: "huerai",
      //   server: "http://10.168.1.199:88/bbcareDeploy",
      //   oriServer: "http://10.168.1.199:88/bbcareDeploy",
      //   educationServer: "http://10.168.1.199:88/bbcareDeploy",
      //   webServer: "http://10.168.1.199:9020",
      //   tableServer:"http://10.168.1.199:83/huerai"
      // },

    }
})

const app = getApp();
export default app;